package org.hashdb.client.net.nio;

import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.hashdb.client.manager.NioAppContext;
import org.hashdb.client.net.nio.msg.Message;

/**
 * Date: 2024/1/20 17:50
 *
 * @author huanyuMake-pecdle
 * @version 0.0.1
 */
class HashChannelHandler extends ChannelInitializer<NioSocketChannel> {

    private final CodecDispatcher codecDispatcher;
    private final ActMessageHandler actMessageHandler;
    private final ChannelInboundHandler disconnectHandler;

    private final ChannelInboundHandler sessionStateHandler;

    HashChannelHandler(NioAppContext ctx) {
        this.disconnectHandler = ctx.client().disconnectHandler();
        this.sessionStateHandler = ctx.client().sessionStateHandler();
        this.codecDispatcher = new CodecDispatcher(ctx);
        this.actMessageHandler = new ActMessageHandler(ctx.reader());
    }

    private static LengthFieldBasedFrameDecoder frameDecoder() {
        return new LengthFieldBasedFrameDecoder(20 * 1024, 18, 4, 0, 0, true);
    }


    @Override
    protected void initChannel(NioSocketChannel ch) {
        ch.pipeline().addLast(frameDecoder());
        ch.pipeline().addLast(codecDispatcher);
        ch.pipeline().addLast(actMessageHandler);
        ch.pipeline().addLast(disconnectHandler);
        ch.pipeline().addLast(sessionStateHandler);
    }

    public <Req extends Message<?>> ActMessageHandler.RequestBuilder<Req> newRequest(Req request) {
        return actMessageHandler.newRequest(request);
    }
}
